package com.bibrApp.difu.actvity.others;

import androidx.appcompat.app.AppCompatActivity;

import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bibrApp.difu.BeemIntent;
import com.bibrApp.difu.R;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.proto2javabean.FeatureBean;
import com.bibrApp.difu.utils.ClsPublicUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.Protocol;
import com.bibrApp.difu.utils.ToastUtils;
import com.bibrApp.difu.utils.UsbConnectUtils;
import com.bibrApp.difu.utils.usbhid.OnUsbHidDeviceListener;
import com.bibrApp.difu.utils.usbhid.UsbHidDevice;
import com.bushidowallet.core.bitcoin.bip32.ExtendedKey;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.googlecode.protobuf.format.JsonFormat;
import com.satoshilabs.trezor.lib.protobuf.TrezorMessageManagement;

import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class TestActivity extends BaseActivity<OtherPresenter> implements IOtherView {

    @BindView(R.id.edittext)
    EditText editText;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    private UsbConnectUtils usbConnectUtils;

    Handler handler = new Handler();

    @Override
    protected void initPresenter() {
        presenter = new OtherPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_test;
    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void success(String msg) {

    }

    @Override
    public void initView() {
        /*usbConnectUtils = UsbConnectUtils.getInstance();
        usbConnectUtils.setLishener(new UsbConnectUtils.OnUsbConnectLishener() {
            @Override
            public void onConnect() {
                showToast("onConnect");
            }

            @Override
            public void onDisconnect() {
                showToast("onDisconnect");
            }

            @Override
            public void onReadData(List<byte[]> data) {
                showToast("onReadData");
                Log.i("ttt", Protocol.decode(data));
                String decodeStr = Protocol.decode(data);
                tvInfo.append("\n解码之后：" + Protocol.decode(data));
                try {
                    TrezorMessageManagement.Features features = TrezorMessageManagement.Features.parseFrom(ClsPublicUtils.hexToBytes(decodeStr));
                    String asJson = JsonFormat.printToString(features);
                    tvInfo.append("\nFeatureBean：" + asJson);

                    Log.d("dj", "=====" + ClsPublicUtils.decodeUnicode(asJson));
                    FeatureBean featureBean = new Gson().fromJson(asJson, FeatureBean.class);
                    Log.d("dj", "=111===" + featureBean);
                    //app.setuAccountName(featureBean.getLabel());
//                    if (featureBean != null) {
//                        IntentUtil.toActivity(UAccountActivity.class, TestActivity.this);
//                        finish();
//                    } else {
//                        ToastUtils.ShowToast(TestActivity.this, "初始化不成功，请重新连接");
//                    }
                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        handler.postDelayed(() -> {
            usbConnectUtils.init(this);
        }, 1000);*/

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (usbConnectUtils != null) {
            usbConnectUtils.release(true);
        }
    }
    private Web3j mWeb3j = Web3jFactory.build(new HttpService("https://ropsten.infura.io/1UoO4I/"));

    @OnClick(R.id.button)
    public void buttonClick() {
        try {
            /*Web3j web3j = Web3jFactory.build(new HttpService("https://ropsten.infura.io/"));*/
            String addressStr = "0x3C2D8eC7206f4c3B81C4C79DCA1A667327a8163F";

            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    EthGetTransactionCount ethGetTransactionCount = null;
                    try {
                        ethGetTransactionCount = mWeb3j.ethGetTransactionCount(
                                addressStr, DefaultBlockParameterName.LATEST).send();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    BigInteger nonce = Objects.requireNonNull(ethGetTransactionCount).getTransactionCount();
                    Log.d("dj","===nonce==="+nonce);
                }
            });

            ExtendedKey extendedKey =  ExtendedKey.ExtendedKeyParser.parse("xpub6Etvxu748uec9MefaDQGWUmjHLWhkmPamvGuAGAFLWyQEkEQKiBkr2sQRxeMBMmULtN5nqeze9QHvMTjZcgwHr69Jj2aibVGnA96vTDWYDZ",true);
            Log.d("dj","====extendedKey===="+extendedKey.toString());
            Log.d("dj","====extendedKey===="+extendedKey.getPublicHex());
            Log.d("dj","====extendedKey===="+extendedKey.getFingerPrint());
            Log.d("dj","====extendedKey===="+ClsPublicUtils.bytesToHex(extendedKey.getChainCode()));
        } catch (Exception e) {
            e.printStackTrace();
        }
       /* String test = "AQAAAAABAvpzsi9baxZQ5m4lnzcyJJRVRL5cFl0PngH/5MZ8RRHOAAAAABcWABSxqzq48d+Wq5MfouzMTrry17FB8/////8=\n" +
                "1+rJscNXaUcIvCMlN3pNZYCtwIVBWy6kD4NkwVtq1IUAAAAAFxYAFLGrOrjx35arkx+i7MxOuvLXsUHz/////w==\n" +
                "AgAAAAAAAAAAF6kURgUzCqfsf1/ymsjfBHhKxuNkVRmH\n" +
                "8xEAAAAAAAAZdqkUOxW1ejYvXwk1d/oexu5hspzxEzmIrA==\n" +
                "4aNH1ykb4uWyHGK9RcuVYAEhA713w2OagkoXaC5lHWaAj9e20fbunEWfjD0akLxdHru5\n" +
                "AkcwRAIgMdUs30CUDUx7XuxsiAv8MbrZ0GYYyegj8bFA9g/0zAQCIA6D5dd+3u9XP6UpSpdcZJza\n" +
                "XJ+HIqm1ewFOzUmBbqpvASEDvXfDY5qCShdoLmUdZoCP17bR9u6cRZ+MPRqQvF0eu7kAAAAA";
        String test1 = "zqUsCihFL53NVvnKATCBMxw5nwo2SUxcqow3GBSFGWE=";

//        byte by[] = android.util.Base64.decode(test, Base64.DEFAULT);
        String str = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                str = ClsPublicUtils.bytesToHex(android.util.Base64.decode(test, Base64.DEFAULT));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        /*Log.d("dj", "======" + str);
        presenter.broadcastBtcTx(str);*/
        /*byte by[] = new byte[0];
        try {
            by = ByteString.copyFrom(test,"gbk").toByteArray();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for(int i =0 ; i < by.length ; i ++){
            Log.d("dj", "======"+by[i]);
        }*/
        /*int ret = -100;
        TrezorMessageManagement.Initialize.Builder initBuild = TrezorMessageManagement.Initialize.newBuilder();
        TrezorMessageManagement.Initialize initialize = initBuild.build();//组装成对应的protobuf文件中的方法
        byte[] init = initialize.toByteArray();//转成16进制

        if (!usbConnectUtils.isConnected()) {
            showToast("没有建立连接");
            return;
        }
        //添加协议
        List<byte[]> bytes = Protocol.encode(0, init);
        // 1,发送准备命令
        //通过usb hid传输数据给u盾
        for (int i = 0; i < bytes.size(); i++) {
            int write = usbConnectUtils.write(bytes.get(i));
            if (write >= 0) {
                showToast("发送成功" + write);
            }
        }*/

    }

}
